<?php
namespace control;
// 资产处置
class assetCutClass extends adIndexClass
{
	private const page    = 'assetCut';         # 权限
	private const table   = 'asset_cut';        # 数据表
	private const tableMx = 'asset_cut_detail'; # 子表
	private const title   = '资产处置';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "处置单号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'type'  => [
                        'name'  => '处置方式',
                        'width' => 300,
                    ],
                    'stid'         => [
                        'name'  => '制单人',
                        'width' => 300,
                    ],
                    'date'          => [
                        'name'  => '处置日期',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "处置单号" => text(array("name" => "orderNo")),
                    "处置原因"   => select(["name" => "type", 'option' => explode('，', para('assetCutReasonOption'))]),
                    "制单人" => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                ],
                [
                    "处置日期" => text(
                        [
                            'name' => 'date',
                            'laydate' => ['range' => '~', 'type' => 'date'],
                        ]
                    ),
                    "状态" => select(["name" => "state", 'option' => ['制单', '审核中', '已通过']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*固定资产入口页*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $root   = $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . self::getId() . '&acid=' . $this->post('objId');
            $button .= "<span class='spanButton' onclick=\"newIframe('新增资产处置','" . $root . "')\">新建</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*固定资产列表*/
	public function homeSearch()
	{
		//查询结果
		$where = ' 1=1 ';
		$equal = [
			'type'  => $this->post('type'),
			'state' => $this->post('state'),
			'stid'  => $this->post('stid'),
			'coid'  => self::$coid,
		];
		$like  = [
			'orderNo' => $this->post('orderNo'),
		];
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);

		$where .= self::timeComparison($this->post('date'), 'date', 'date');
		$where .= $this->seeSelf(self::page, 'stid');
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page  = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => ["title" => "固定资产详情", "click" => "newIframe('固定资产详情','" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $array['id'] . "')"],
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	public function editPage(): string
	{
	    $id = $this->get('id')?:suiji();
		$info        = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "fun" => "subForm('" . self::page . "EditPageForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editPageEdit')",
            'style' => 'li-btn-blue-bg',
        ];
        $endDate = $info['date']?:$this->date;
        $tr[] = ['', '卡片编码', '名称', '品牌', '规格型号','使用人部门','使用人', '存放地点', '处置数量', '资产残值','清理收入','清理费用', '备注'];
        if ($this->get('sourceId')){
            $info['text'] = '资产盘点处置';
            $asset_inventory = query('asset_inventory',"id = '".$this->get('sourceId')."'");
            $result = find(array('table' => 'asset_inventory_detail', 'where' => "orderId = '$asset_inventory[id]' and state = '未盘点' and id not in (select sourceId from asset_cut_detail where coid = '".self::$coid."' and sourceTable = 'asset_inventory_detail') order by list"));
            foreach ($result['array'] as $k=>$array){
                $asset = query('asset', " id = '$array[atid]'");
                $ratio = assetManagementClass::monthRatio($asset['depreciationMethod'],$asset['discountYear'],$asset['money'],$asset['purchaseMoney'],$asset['depreciationMoney'],$asset['purchaseDate'],$endDate,1);
                $monthDecMoney =assetManagementClass::monthDecMoney($asset['depreciationMethod'],$asset['purchaseMoney'],$ratio/100,$asset['purchaseDate'],$endDate,$asset['discountYear'],$asset['money'],$asset['depreciationMoney']);
                $discountMoney = assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],$asset['depreciationMoney'],$endDate);

                $tr[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' => suiji())) .
                    hidden(array('name' => 'atid[]', 'value' => $array['atid'])).
                    hidden(array('name' => 'sourceId[]', 'value' => $array['id'])),
                    $asset['orderNo'],
                    $asset['name'],
                    $asset['brand'],
                    $asset['model'],
                    $asset['userDepartment'],
                    self::findStaff($asset['user']),
                    $asset['storage'],
                    $asset['num'],
                    round($asset['purchaseMoney']-$discountMoney,2),
                    text(array('name' => 'income[]', 'type' => 'number')),
                    text(array('name' => 'fee[]', 'type' => 'number')),
                    text(array('name' => 'mxText[]', 'class' => 'text')),
                ];
            }
        }else{
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $k=>$array) {
                $asset = query('asset', " id = '$array[atid]'");
                $ratio = assetManagementClass::monthRatio($asset['depreciationMethod'],$asset['discountYear'],$asset['money'],$asset['purchaseMoney'],$asset['depreciationMoney'],$asset['purchaseDate'],$endDate,1);
                $monthDecMoney =assetManagementClass::monthDecMoney($asset['depreciationMethod'],$asset['purchaseMoney'],$ratio/100,$asset['purchaseDate'],$endDate,$asset['discountYear'],$asset['money'],$asset['depreciationMoney']);
                $discountMoney = assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],$asset['depreciationMoney'],$endDate);

                $tr[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                    hidden(array('name' => 'atid[]', 'value' => $array['atid'])).
                    hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])),
                    $asset['orderNo'],
                    $asset['name'],
                    $asset['brand'],
                    $asset['model'],
                    $asset['userDepartment'],
                    self::findStaff($asset['user']),
                    $asset['storage'],
                    $array['num'],
                    round($asset['purchaseMoney']-$discountMoney,2),
                    text(array('name' => 'income[]', 'type' => 'number', 'value' => $array['income'])),
                    text(array('name' => 'fee[]', 'type' => 'number', 'value' => $array['fee'])),
                    text(array('name' => 'mxText[]', 'class' => 'text', 'value' => $array['text'])),
                ];
            }
        }

        $list = $this->listTable(array('tr' => $tr, 'end' => true));
        $but = <<<efo
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name=assetCutEditPageForm]').serialize())">选择固定资产</span>
                 <input id="barcode" style="margin-left: 20px" type="text" placeholder="输入或扫码"/>
                 <label class="checkbox" style="color: #757575;"><input id="cancel_button" type="checkbox" ><span></span>&nbsp;撤销</label>
efo;
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '处置方式' => select([
                        "name"   => "type",
                        "title"  => "请选择",
                        'value'  => $info['type'],
                        'option' =>  para('assetCutReasonOption','，'),
                    ]),
                    must . '处置日期' => text(['name' => "date", 'class' => 'text', 'value' => $info['date']?:$this->date, 'laydate' => []]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]) . hidden(['name' => 'id', 'value' => $info['id'] ?:$id]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '明细',
            'button' => $but,
            'html' => $list,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
		]);
        $data['html'] .= $this->js();
		//返回
		return $this->tab($data);
	}
    /**
     * JS
     * @return string
     */
    public function js(): string
    {
        $cla = self::page;
        return <<<eof
<script>
/***扫码操作***/
$("#barcode").on('keydown',function(event) {
    if (event.keyCode===13){
        let code = $(this).val();//条码
        if (!code){
            msg('未找到条码','error')
            return '';
        }
        //判断是否是撤销操作
        if ($("#cancel_button").is(":checked")){
            //撤销
            $.post(root+'control/adIndex.html?cla={$cla}&fun=getMaterial',{code:code},function(res) {
                  if (res.warn===2){
                      $("#materialTable").find("input[name='atid[]']").each(function() {
                           if (res.data === $(this).val()){
                               $(this).parent().parent().remove();
                           }
                      });
                  }else{
                      msg(res.warn,'error');
                  }
            },'json')
        }else{
            //添加
             $.post(root+'control/adIndex.html?cla={$cla}&fun=getMaterial',{code:code},function(res) { 
                 if (res.warn===2){
                       $.post(root+'control/adIndex.html?cla={$cla}&fun=addMxEdit',{materialId:res.data,classify:'barcode'},function(res) {
                           if (res.warn ==2){
                               $("#materialTable tbody").append(res.html);
                           }else{
                               msg(res.warn,'error');
                           }
                           
                       },'json')
                  }else{
                      msg(res.warn,'error');
                  }
             },'json')
        }
    }
});



function addRow(){
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
             if (res.warn ==2){
              $('#assetCutAddMx').hide()
                $("#materialTable tbody").append(res.html);
                resetNumber($("#materialTable tbody"))
           }else{
               msg(res.warn,'error');
           }
            
        },'json');
}

</script>
eof;

    }
	/*基本资料新增或修改-异步处理*/
	public function editPageEdit()
	{
		$id         = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId');
        $atidArr = $this->post('atid');
        $incomeArr = $this->post('income');
        $feeArr = $this->post('fee');
        $mxTextArr = $this->post('mxText');
        $sourceIdArr = $this->post('sourceId');
		$field      = [
			'type' => $this->post('type'),
			'date' => $this->post('date'),
			'text' => $this->post('text'),
		];
		$annotation = [
			'type' => '处置方式',
			'date' => '处置日期',
		];
		$rules      = [
			'type' => 'required',
			'date' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择处置明细';
        } elseif (static::is_null_array($atidArr)) {
            $json['warn'] = '请选择处置明细';
        } elseif (!empty($info['id']) && $info['state'] != '制单') {
            $json['warn'] = '此单据不是制单状态，不能编辑';
        }  else {
			$where = " id = '$id' ";
			$info  = query(self::table, $where);
            $this->startTrans();
			// 职位名称
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'table'   => self::table,
                    'prefix'  => 'ZCCZ' . date('Ymd'),
                    'default' => '001',
                ],$field);
				$field        = array_merge($field, [
					'id'      => $id,
					'coid'    => self::$coid,
					'orderNo' => $orderNo,
					'state'   => '制单',
					'stid'    => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::tableMx, "id = '$nid'");
                $asset = query('asset',"id = '$atidArr[$k]'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableMx,
                        "field" => [
                            'atid' => $atidArr[$k],
                            'income' => $incomeArr[$k],
                            'fee' => $feeArr[$k],
                            'num' => $asset['num'],
                            'text' => $mxTextArr[$k],
                            'sourceId'=>$sourceIdArr[$k],
                            'sourceTable'=>'asset_inventory_detail'
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableMx,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'atid' => $atidArr[$k],
                            'income' => $incomeArr[$k],
                            'fee' => $feeArr[$k],
                            'num' => $asset['num'],
                            'text' => $mxTextArr[$k],
                            'sourceId'=>$sourceIdArr[$k],
                            'sourceTable'=>'asset_inventory_detail'
                        ],

                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】' . (!empty($field['title']) ? "，标题【{$field['title']}】" : '');
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			}else{
			    $this->rollback();
            }
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 审核按钮
	 *
	 * @param $info
	 * @return array
	 */
	public function auditButton($info): array
	{
		$button = [];
		if ($info['state'] == '制单' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
			$button[] = [
				"name"  => '提交审批',
				"type"  => "弹出层",
				"cla"   => 'audit',
				"fun"   => "operate",
				'style' => 'li-btn-blue-bg',
				"post"  => [
					"act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'name'    => '资产处置',
						'table'   => self::table,
						'process' => [
							// 预览函数
							'detail' => [
								'cla' => $this->get('cla'),
								'fun' => 'detail',
							],
							// 保存函数
							'save'   => [
								'cla' => $this->get('cla'),
								'fun' => 'editPageEdit',
							],
							//执行发起时验证函数
							'before' => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
							//完成发起后执行函数
							'after'  => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
						],
					], 320)),
				],
			];
		}
		// 审批并判断是否有权限
		if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name"  => '审批',
                "type"  => "弹出层",
                "cla"   => 'audit',
                "fun"   => "operate",
                // 以下参数固定格式
                "post"  => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table'   => self::table,
                        // 当前状态
                        'state'   => $info['state'],
                        // 变更
                        'field'   => ['state'],   //变更字段 可多个
                        'value'   => [
                            'state' => ['制单', '已通过'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after'  => [
                                'cla'  => $this->get('cla'),
                                'fun'  => 'cutDone',
                                'data' => ['id' => $info['id']],
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
			$button[] = [
				"name" => '添加审批人',
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table' => self::table,
					], 320)),
				],
			];
			$button[] = [
				"name" => '转交',
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table' => self::table,
					], 320)),
				],
			];

		}

		// 撤销审批
		if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] == '审核中') {
			$button[] = [
				"name" => '撤销审批',
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table'   => self::table,
						// 当前状态
						'state'   => $info['state'],
						// 变更
						'field'   => ['state'],   //变更字段 可多个
						'value'   => [
							'state' => ['制单'],
						],
						'process' => [
							//完成发起后执行函数
							'after' => [
								'cla' => $this->get('cla'),
//								'fun' => 'cancelFun',
//                                'data'=>['id'=>$info['id']]
							],
						],
					], 320)),
				],
			];
		}
		return $button;
	}

	public function detail(): string
	{
		$info = query(self::table, " id = '" . $this->get('id') . "' ");
		if (!$this->power(self::page, "see")) {
			$html = "你没有查看权限";
		} elseif (!$this->get('id')) {
			$html = "ID为空";
		} elseif (!$info['id']) {
			$html = "未找到此信息";
		} else {
			$data = [
				"id" => $info['id'],
			];
			//按钮
			$button = [];
            //审核按钮
            $button = array_merge($button, $this->auditButton($info));
			if ($info['state'] == '制单') {

				if ($this->power(self::page, "edit")) {
					$button[] = [
						"name"  => "编辑",
						"type"  => "顶部页卡",
						"title" => "编辑用户",
						"url"   => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . $info['id'],
					];
				}
                if ($this->power(self::page, "del")) {
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla"  => $this->get('cla'),
                        "fun"  => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
			}
            $endDate = $info['date'];
			// 子表
			$mxtr[]   = ['卡片编码', '名称', '品牌', '规格型号', '使用人部门', '使用人', '存放地点', '处置数量', '资产残值(' . static::$unit . ')','清理收入','清理费用', '备注'];
			if ($info['id']) {
				//订单明细
				$all = self::sqlFind("SELECT * FROM " . self::tableMx . " WHERE orderId = '$info[id]' ORDER BY time ");
				foreach ($all as $array) {
					$asset    = query('asset', " id = '{$array['atid']}' ");
                    $ratio = assetManagementClass::monthRatio($asset['depreciationMethod'],$asset['discountYear'],$asset['money'],$asset['purchaseMoney'],$asset['depreciationMoney'],$asset['purchaseDate'],$endDate,1);
                    $monthDecMoney =assetManagementClass::monthDecMoney($asset['depreciationMethod'],$asset['purchaseMoney'],$ratio/100,$asset['purchaseDate'],$endDate,$asset['discountYear'],$asset['money'],$asset['depreciationMoney']);
                    $discountMoney = assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],$asset['depreciationMoney'],$endDate);

                    $mxtr[]   = [
						$asset['orderNo'],
						$asset['name'],
						$asset['brand'],
						$asset['model'],
						$asset['userDepartment'],
						self::findStaff($asset['user']),
						$asset['storage'],
						$array['num'],
                        round($asset['purchaseMoney']-$discountMoney,2),
                        $array['income'],
                        $array['fee'],
                        $array['text']
					];
				}
			}
			// 生成子表单页面
			$detailHtml =$this->listTable(['tr' => $mxtr]);
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				 [
					[
                        "处置方式" => $info['type'],
                        "处置日期" => $info['date'],
                        "单号" => $info['orderNo'],
                        "制单人"  => self::findStaff($info['stid']),
					],
					[
                        "状态" => $info['state'],
					],
                     [
                         "备注" => pre($info['text']),
                     ],
				],
			]);
            $data['html'] .= $this->detailList([
                'title' => '明细',
                'html' => $detailHtml,
            ]);
            $data['html'] .= $this->detailBlock([
                '流程' => auditClass::auditRecord(self::table, $info['id'])
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 处置
	 *
	 * @param array $data
	 * @return void
	 */
	public function cutDone($data)
	{
		$id     = $data['id'];
		$info   = query(self::table, " id = '$id' ");
		$result = find([
			'table' => self::tableMx,
			'where' => " orderId = '{$info['id']}' ",
		]);
		foreach ((array)$result['array'] as $key => $value) {
			static::update([
				'table' => self::tableMx,
				'field' => [
					'state'    => '已处置',
					'passTime' => $this->time,
				],
				'where' => " id = '{$value['id']}' ",
			]);
			static::update([
				'table' => 'asset',
				'field' => [
					'state' => '已处置',
					'isCut' => 1,
				],
				'where' => " id = '{$value['atid']}' ",
			]);
			static::insert([
				'table' => 'asset_revert',
				'field' => [
					'id'   => self::getNo(),
					'coid' => self::$coid,
					'atid' => $value['atid'],
					'type' => '处置',
				],
			]);
		}
	}


    /**
     * 添加固定资产
     *
     * @return bool|string
     */
    public function addMx(): bool|string
    {
        $html =
            text(["name" => "acid", "title" => "分类"])
            . text(["name" => "orderNo", "title" => "编码"])
            . text(["name" => "name", "title" => "名称"])
            . text(["name" => "model", "title" => "规格"])
            . hidden(array('name' => 'recordDate', 'value' => $this->post('recordDate')))
            . hidden(array('name' => 'atid', 'value' => $this->post('atid') ? implode(',', $this->post('atid')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(["title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button]);
    }

    /**
     *添加固定资产
     */
    public function addMxSearch(): bool|string
    {
        $materialId = $this->post('atid') ? explode(',', $this->post('atid')) : [];

        $where = (empty($this->post('acid'))) ? ' 1=1 ' : " acid  in (select acid from `asset_catalog` where name LIKE '%{$this->post('acid')}%') ";
        $and = " and isCut = 0 and id not in ('" . implode("','", $materialId) . "')";
        $like = [
            'name' => $this->post('name'),
            'orderNo' => $this->post('orderNo'),
            'model' => $this->post('model'),
        ];
        $equal = [
            'coid' => self::$coid,
        ];

        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "asset",
            "where" => $where,
            'pageNum' => 50,
            "order" => " `time` ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll, '分类', '固定资产编码', '名称', '品牌', '规格'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            $tr[] = [
                $this->dominate($dominate),
                assetCatalogClass::getCatalogName($array['acid']),
                $array['orderNo'],
                $array['name'],
                $array['brand'],
                $array['model'],
            ];
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])).
            hidden(array('name' => 'recordDate', 'value' => $this->post('recordDate'))) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * 添加
     *
     * @return bool|string
     */
    public function addMxEdit(): bool|string
    {
        $mxIdArr = $this->post('mxId');
        $materialId = $this->post('materialId');
        $classify = $this->post('classify');//扫码添加类型
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif ($classify !== 'barcode' && (empty($mxIdArr) || !is_array($mxIdArr))) {
            $json['warn'] = '请选择固定资产';
        } elseif ($classify === 'barcode' && empty($materialId)) {
            $json['warn'] = '请选择固定资产';
        } else {
            $json['html'] = '';
            if ($classify === 'barcode') {
                $mxIdArr[] = $materialId;
            }
            $endDate = $this->post('endDate')?:$this->date;
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $asset = query('asset', " id = '$mxId'");
                $ratio = assetManagementClass::monthRatio($asset['depreciationMethod'],$asset['discountYear'],$asset['money'],$asset['purchaseMoney'],$asset['depreciationMoney'],$asset['purchaseDate'],$endDate,1);
                $monthDecMoney =assetManagementClass::monthDecMoney($asset['depreciationMethod'],$asset['purchaseMoney'],$ratio/100,$asset['purchaseDate'],$endDate,$asset['discountYear'],$asset['money'],$asset['depreciationMoney']);
                $discountMoney = assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],$asset['depreciationMoney'],$endDate);

                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' =>suiji())) .
                    hidden(array('name' => 'atid[]', 'value' => $mxId)).
                    hidden(array('name' => 'sourceId[]', 'value' => '')),
                    $asset['orderNo'],
                    $asset['name'],
                    $asset['brand'],
                    $asset['model'],
                    $asset['userDepartment'],
                    self::findStaff($asset['user']),
                    $asset['storage'],
                    $asset['num'],
                    round($asset['purchaseMoney']-$discountMoney,2),
                    text(array('name' => 'income[]', 'type' => 'number')),
                    text(array('name' => 'fee[]', 'type' => 'number')),
                    text(array('name' => 'mxText[]', 'class' => 'text')),
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false, 'end' => true));
        }
        return json_encode($json, 320);
    }


	// 操作中转
	public function operate()
	{
		$act    = $this->post('act') ?? '';
		$pwd    = false; // 需要密码
		$form   = $power = '';
		$append = [];
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'isDelete';
				$form     = self::page . 'OperateForm, listForm';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'append'   => $append,
			]);
		}

		resp:
		return json_encode($json, 320);
	}


	// 确认删除信息
	public function isDelete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除" . self::title . "的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			// 判断field
			$fieldKey   = 'state';
			$fieldVlaue = '制单';

			foreach ($array as $id) {
				$where = " id = '$id' ";
				$info  = query(self::table, $where);
				if ($info['id']) {
					if ($info[$fieldKey] !== $fieldVlaue) {
						$text .= self::title . "【{$info['id']}】非{$fieldVlaue}状态，无法删除<br>";
						continue;
					}
					// 删除表
					delete([
						"table" => self::table,
						"where" => $where,
					]);
                    delete([
                        "table" => self::tableMx,
                        "where" => "orderId = '$id'",
                    ]);
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog","where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message","where" => " typeid = '$id' "));
					//添加记录
					$text .= "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】，编号【{$info['orderNo']}】<br>";
					$x++;
				}
			}

			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "删除了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}

		resp:
		return json_encode($json, 320);
	}

}
